// Author: Cezary Tomczak [www.gosu.pl] [cagret#gmail]

var dat_dir = realDir+'dat\\';
var export_dir = realDir+'export\\';
var projects_file = dat_dir+'projects.dat';
var tasks_file_tpl = dat_dir+'tasks-%id%.dat';
var tasks_file = null;

var language2_file = realDir+'language.dat';
var language2 = 'en';
if (File.exists(language2_file)) {
	language2 = File.read(language2_file);
}

if (!Dir.exists(dat_dir)) {
    Dir.create(dat_dir);
}
if (!Dir.exists(export_dir)) {
    Dir.create(export_dir);
}

var projects = {
    'selected': 1,
    'seq_id': 1,
    'rows': {
        '1' : {'id':1, 'date':date_toDay(), 'name':('pl' == language2 ? 'Pierwszy projekt' : 'First project'), 'rate':'', 'currency': default_currency}
    }
};
var curr_project = projects.rows[projects.selected];
var tasks_tpl = {
    'active': -1,
    'seq_id': 0,
    'rows': {}
};
var tasks = tasks_tpl;

// update 1.0 >> 1.1
function update_1_1()
{
    var tasks_old_file = realDir+'tasks.dat';
    var rate_old_file = realDir+'rate.dat';
    var tasks_new_file = dat_dir+'tasks-1.dat';
    if (File.exists(tasks_old_file) && !File.exists(projects_file) && !File.exists(tasks_new_file))
    {
        var rows = JSON.parse(File.read(tasks_old_file));
        var rows2 = {};
        var active = -1;
        for (var i = rows.length - 1; i >= 0; i--) {
            var row = rows[i];
            var id = i+1;
            rows2[id] = {
                'id': id,
                'day': row.day,
                'time': row.time,
                'name': row.name
            };
            if (row.active) {
                active = id;
            }
        }
        var tasks_new = {
            'active': active,
            'seq_id': rows.length,
            'rows': rows2
        };

        if (File.exists(rate_old_file)) {
            projects.rows[1].rate = Number(File.read(rate_old_file));
        }
        File.write(tasks_new_file, JSON.stringify(tasks_new));
        File.write(projects_file, JSON.stringify(projects));
        File.remove(tasks_old_file);
        if (File.exists(rate_old_file)) {
            File.remove(rate_old_file);
        }

        var files = Dir.readFiles(realDir);
        for (var i = 0; i < files.length; i++) {
            if (files[i].match(/export(\-\d\d\d\d\-\d\d\-\d\d\.html)$/i)) {
                var new_html = export_dir+'export-'+curr_project.id+RegExp.$1;
                File.rename(files[i], new_html);
            }
        }
    }
}
update_1_1();

function task_save(onlyInit)
{
    tasks_file = tasks_file_tpl.replace(/%id%/, curr_project.id);
    File.write(tasks_file, JSON.stringify(tasks));
    if (!onlyInit) {
        total_update();
    }
}
function task_save_new(id)
{
    var file = tasks_file_tpl.replace(/%id%/, id);
    File.write(file, JSON.stringify(tasks_tpl));
}
function project_save()
{
    File.write(projects_file, JSON.stringify(projects));
}
function project_load(id, onlyInit)
{
    projects.selected = id;
    project_save();
    curr_project = projects.rows[id];
	switch_currency(curr_project.currency, !onlyInit);
    tasks_file = tasks_file_tpl.replace(/%id%/, curr_project.id);
    tasks = JSON.parse(File.read(tasks_file));
    if (!onlyInit) {
        task_refresh();
    }
    __micro_reset();
}

if (!File.exists(projects_file) && !File.exists(tasks_file_tpl.replace(/%id%/, 1))) {
    project_save();
    task_save(true);
}
if (File.exists(projects_file)) {
    projects = JSON.parse(File.read(projects_file));
    project_load(projects.selected, true);
}

function select_project_render()
{
    var sel = '<select id="select_project" onchange="project_load(this.value)">%opt%</select>';
    var opt = '';
    var rows = projects_rows_latest();
    for (var i = 0; i < rows.length; i++) {
        var proj = rows[i];
        opt += '<option value="'+proj.id+'" '+(curr_project.id == proj.id ? 'selected="selected"':'')+'>'+proj.name+'</option>';
    }
    sel = sel.replace(/%opt%/, opt);
    $('select_project_container').innerHTML = sel;
}
function tasks_rows()
{
    var ret = [];
    for (var id in tasks.rows) {
        ret.push(tasks.rows[id]);
    }
    return ret;
}
function tasks_rows_latest()
{
    var ret = tasks_rows();
    function sortLatest(a, b)
    {
        return b.id - a.id;
    }
    ret.sort(sortLatest);
    return ret;
}
function projects_rows()
{
    var ret = [];
    for (var id in projects.rows) {
        ret.push(projects.rows[id]);
    }
    return ret;
}
function projects_rows_latest()
{
    var ret = projects_rows();
    function sortLatest(a, b)
    {
        return b.id - a.id;
    }
    ret.sort(sortLatest);
    return ret;
}
function maxProjectId()
{
    var max = null;
    for (var i in projects.rows) {
        if (max === null) {
            max = i;
        } else {
            if (i > max) {
                max = i;
            }
        }
    }
    return max;
}
function date_toDay()
{
    return getIsoDate(new Date()).substr(0,10);
}
function getDay(d)
{
    if (!d) {
        d = getIsoDate(new Date());
    }
    var day = d.substr(8, 2);
    var month = d.substr(5, 2);
    return day+'.'+month;
}
function getTime(t)
{
    if (!t) {
        return 0;
    }
    t = String(t);
    if (t.match(/^(\d+)[:,\.](\d\d)$/)) {
        var h = RegExp.$1;
        var m = RegExp.$2;
        h = h.replace(/^0+/, '');
        m = m.replace(/^0+/, '');
        return Number(h) * 60 + Number(m);
    }
    if (t.match(/^\d+$/)) {
        var h = t;
        h = h.replace(/^0+/, '');
        return Number(h) * 60;
    }
    if (t.match(/^[:,\.](\d\d)$/)) {
        var m = RegExp.$1;
        m = m.replace(/^0+/, '');
        return Number(m);
    }
    return -1;
}
function formatDay(day)
{
    if (day.match(/^(\d+)([,\-\.])(\d+)$/)) {
        var d = RegExp.$1;
        var dot = RegExp.$2;
        var m = RegExp.$3;
        if (d.length == 1) {
            d = '0'+d;
        }
        if (m.length == 1) {
            m = '0'+m;
        }
        return d+'.'+m;
    }
    return day;
}
function formatTime(t)
{
    if (!t) {
        return '0:00';
    }
    var h, m;
    h = (String(t / 60)).replace(/\.\d+/g, '');
    m = t % 60;
    return h + ':' + padZeros(m, 2);
}
function escapeTags(s)
{
    return s.replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function __micro_stop()
{
    __micro = false;
}
function __micro_reset()
{
    __micro = time_start();
}
function task_interval_sec()
{
    if (!__micro) return;

    var id = tasks.active;
    if (id == -1) return;

    var secs = time_end(__micro);
    if (secs >= 60) {
        __micro += 60;
        tasks.rows[id].time++;
        task_save();
        secs = time_end(__micro);
    }

    secs = String(secs).replace(/\.\d+/, '');
    $('task_time_'+id).innerHTML = formatTime(tasks.rows[id].time)+'<small>.'+padZeros(secs, 2)+'</small>';
}
function task_export()
{
    var date = getIsoDate(new Date()).substr(0,10);
    var file = export_dir+'export-'+curr_project.id+'-'+date+'.html';

    var cont = File.read(realDir+'style.css');
    var style = '<style type="text/css">';
    style += cont;
    style += 'body { margin: 1em; }';
    style += '</style>';

    var html = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>'+curr_project.name+' ('+date+')</title>'+style+'</head><body>';

    var rows = tasks_rows_latest();
    var totalTime = total_time();
    var rate = curr_project.rate;

    html += '<h1>'+curr_project.name+' ('+date+')</small></h1>';
    html += '<p>';
    if (rows.length) {
        html += lang.total_time+': <b>'+formatTime(totalTime)+'</b>';
    }
    if (rows.length && rate) {
        html += '&nbsp;&nbsp;<i>|</i>&nbsp;&nbsp;';
        html += lang.total_amount+': <b>'+time_round((totalTime/60)*rate)+'</b> '+curr_currency();
        html += '&nbsp;&nbsp;<i>|</i>&nbsp;&nbsp;';
        html += lang.rate+': <b>'+rate+'</b> '+curr_currency();
    }
    html += '</p>';

    html += '<table class="ls" cellspacing="1" cellpadding="0" width="522"><tr><th width="10%">'+lang.day+'</th><th>'+lang.task+'</th><th width="10%">'+lang.time+'</th></tr>';
    for (var i = 0; i < rows.length; i++) {
        var task = rows[i];
        html += ('<tr><td align="center">'+formatDay(task.day)+'</td><td>'+nl2br(task.name)+'</td><td align="center">'+formatTime(task.time)+'</td></tr>').replace(/<td/g, '<td style="background: #eee; "');
    }
    html += '</table>';

    html += '</body></html>';
    File.write(file, html);
    shell.Run('"'+file+'"');
}
var tabs = ['tab_tasks', 'tab_projects', 'tab_info'];
function tab_show(id)
{
    for (var i = 0; i < tabs.length; i++) {
        if (tabs[i] == id) {
            if ($(tabs[i]+'_menu')) {
                $(tabs[i]+'_menu').style.display = '';
            }
            $(tabs[i]).style.display = 'block';
        } else {
            if ($(tabs[i]+'_menu')) {
                $(tabs[i]+'_menu').style.display = 'none';
            }
            $(tabs[i]).style.display = 'none';
        }
    }
    if ('tab_tasks' == id) {
        task_refresh();
        __micro_reset();
    }
    if ('tab_projects' == id) {
        project_refresh();
        __micro_stop();
    }
    if ('tab_info' == id) {
        __micro_stop();
    }
}
function nl2br(s)
{
	return s.replace(/(\r|n\|r\n)/g, '<br>\r\n');
}